package com.geen.tuoke.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.geen.tuoke.R
import com.geen.tuoke.bean.Label
import com.geen.tuoke.bean.request.UpdateTaskRequest
import com.geen.tuoke.databinding.DialogTaskPhoneAutoCallBinding
import com.geen.tuoke.ui.adapter.LabelAdapter
import com.geen.tuoke.utils.ext.dp2px
import com.geen.tuoke.utils.ext.toastShort
import com.geen.tuoke.widget.dialog.DialogViewHolder
import com.geen.tuoke.widget.dialog.XXDialog
import com.qmuiteam.qmui.kotlin.onClick
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @Desc 号码详情弹窗
 */
class DialogTaskPhoneAutoCall(
    context: Context,
    private var onStopCall: () -> Unit,
    private var onNextCall: () -> Unit,
    private val onClickCustomer: () -> Unit,
    private val updateTask: (updateRequest: UpdateTaskRequest) -> Unit
) : XXDialog(context, R.layout.dialog_task_phone_auto_call) {

    lateinit var adapter: LabelAdapter
    private var mBinding: DialogTaskPhoneAutoCallBinding? = null

    private var mainScope = MainScope()
    private var updateTaskRequest: UpdateTaskRequest? = null
    private var selectLabs = mutableListOf<Label>()

    init {
        setWidthAndHeight(dp2px(288f), 0)
        setCanceledOnTouchOutside(false)
        setCancelAble(false)
        setDialogDismissListener {
            mainScope.cancel()
        }


        mBinding?.run {
            val llList = listOf<LinearLayout>(llConnectNo, llEmptyNumber)
            llList.forEach { contains ->
                contains.onClick {
                    //全部置为未选择
                    llList.map {
                        for (i in 0 until it.childCount) {
                            it.getChildAt(i).isSelected = false
                        }
                    }
                    //把自己置为选中状态
                    for (i in 0 until (it as LinearLayout).childCount) {
                        it.getChildAt(i).isSelected = true
                    }
                    //更新
                    if (checkEmptyNumber.isSelected) {
                        updateTaskRequest?.tag = 2
                    }
                    if (checkUnConnect.isSelected) {
                        updateTaskRequest?.tag = 0
                    }
                    updateTask(updateTaskRequest!!)
                }
            }

            initRV()
            tvStopCall.onClick {
                mainScope.cancel()
                onStopCall()
                dismiss()
            }
            tvNextCall.onClick {
                mainScope.cancel()
                onNextCall()
                dismiss()
            }
            llCustomer.setOnClickListener {
                mainScope.cancel()
                dismiss()
                onClickCustomer()
            }
        }
        updateTaskRequest = UpdateTaskRequest(0, 0, selectLabs)

    }


    override fun convert(holder: DialogViewHolder) {
        mBinding = DataBindingUtil.bind(holder.convertView)

    }

    fun setLabelData(it: List<Label>?) {
        adapter.setList(it)
    }


    @SuppressLint("NotifyDataSetChanged")
    private fun DialogTaskPhoneAutoCallBinding.initRV() {
        adapter = LabelAdapter()
        rv.layoutManager = GridLayoutManager(context, 3)
        rv.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(
                context
            ).size(dp2px(15f))
                .color(Color.TRANSPARENT).build()
        )
        rv.adapter = adapter

        adapter.setOnItemClickListener { adapter, view, position ->
            val labelInfo = adapter.getItem(position) as Label
            if (labelInfo.isSelect) {
                labelInfo.isSelect = false
                selectLabs.remove(labelInfo)
            } else {
                selectLabs.add(labelInfo)
                labelInfo.isSelect = true
            }
            updateTaskRequest?.labels = selectLabs
            updateTask(updateTaskRequest!!)
            adapter.notifyDataSetChanged()
        }
    }

    /***
     * 设置默认的接通状态
     * @param statusCheckIndex Int
     */
    fun setCheckStatus(statusCheckIndex:Int){
        mBinding?.let {
            when(statusCheckIndex){
                -1->{
                    it.checkEmptyNumber.isSelected = true
                }
                0->{
                    it.checkUnConnect.isSelected = true
                }
                1->{
                    it.checkEmptyNumber.isSelected = false
                    it.checkEmptyNumber.isSelected = false
                }
            }
        }
    }

    //callOutResultByNet  :   0 未接通 1未接通    -1 空号
    fun showAutoDialog(time: Int, mobile: String, callOutResultByNet: Int) {
        showDialog()
        mBinding?.run {
            mainScope = MainScope()
            tvMobile.text = mobile

            tvWaitCall.isVisible = true
            tvNextCall.isVisible = false
            mainScope.launch {

                for (i in (1..time).reversed()) {

                    tvWaitCall.text = "等待回拨${i}秒"
                    delay(1000)

                    if (i == 1) {
                        tvNextCall.isVisible = true
                        tvWaitCall.isVisible = false
                        //显示下一个按钮  如果不按  等待一秒自动触发
                        delay(1000)
                        tvNextCall.performClick()
                    }
                }
            }
        }
        setCheckStatus(callOutResultByNet)
    }

    override fun dismiss() {
        super.dismiss()
        mainScope.cancel()
    }
}